package com.zhiyou100.service;


import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyuncs.exceptions.ClientException;
import com.zhiyou100.application.DateUtil;
import com.zhiyou100.application.SMSUtil;
import com.zhiyou100.dao.UserDao;
import com.zhiyou100.exception.LoginException;
import com.zhiyou100.model.User;

@Service
public class UserSerivceImpl implements UserService{
	@Autowired
	private UserDao userDao;

	//根据手机号获取验证码
	@SuppressWarnings("unused")
	@Override
	public int sendCode(String phone) {
		//根据手机号从数据库获取验证码和验证码发送时间
		User user=userDao.getAllByPhone(phone);
		Long threeMinut = null;
		if(user == null){
			threeMinut = 200L;
		}else{
			threeMinut = DateUtil.drationFromNowTo(user.getCodeSendTime());
		}

		if(threeMinut <180) {
			throw new LoginException(403001,"抱歉，三分钟内不能重复发短信");
		}
		
		//发短信 int(Math.random()*(n-m+1))+m
		int code1=(int) ((Math.random()*(999999-100000+1))+100000);
		
		try {
			SMSUtil.sendSMS(phone, code1);
		} catch (ClientException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(user == null) {
			userDao.addTime(phone,code1);
		}else {
			Date now = new Date();
			userDao.updateTime(phone, code1, now);
		}
		return code1;
	}

	
	//使用手机验证码登录
	@Override
	public User loginByPhoneAndCode(String phone,int code) {
		User saveUser = userDao.getAllByPhone(phone);
		if(saveUser == null) {
			throw new LoginException(403002,"手机号输入有误或用户未注册");
		}
		
		Long fiveMinut = DateUtil.drationFromNowTo(saveUser.getCodeSendTime());
		if(fiveMinut > 300) {
			throw new LoginException(403003,"验证码失效");
		}else if(!saveUser.getCode().equals(code)) {
			throw new LoginException(403004,"验证码输入错误");
		}
		if(saveUser.getName() == null) {
			int name0= (int) ((Math.random()*(999999-100000+1))*100000);
			//随机成一个昵称
			String name=String.valueOf(name0);
			userDao.updataName(saveUser.getId(), saveUser.getPhone(), saveUser.getName());
		}
		return saveUser;
	}

	//根据手机号使用密码登录
	@Override
	public User loginByPhoneAndPassword(String phone,String password) {
		
		User saveUser=userDao.getAllByPhone(phone);
		if(saveUser == null) {
			throw new LoginException(403005,"用户不存在");
		}
		if(!saveUser.getPassword().equals(password)) {
			throw new LoginException(403006,"密码输入有误，请重新输入");
		}
		return saveUser;
	}

	@Override
	public User getUserByphoneAndId(String phone, Integer id) {
		User user=userDao.getUserByPhoneAndId(phone, id);
		return user;
	}

	@Override
	public void update(User user) {
		userDao.update(user);
		
	}

}
